package test_achieve.web;

import com.google.common.base.Strings;
import constant.WebCityId;
import constant.Constant;
import cucumber.api.PendingException;
import org.openqa.selenium.interactions.Actions;
import util.tools.BusinessTools;
import util.tools.CommonTools;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.util.List;

/**
 * Created by chenkuo on
 */
public class OrderMain {

    Login login = new Login();

    @Given("^w已登录并进入在线下单界面：(.+)$")
    public   void wLogInEnterInterface(String username) throws UnknownHostException {
        login.wLoging(username);
        Oneself me = new Oneself();
        me.w进入在线下单界面();
    }



    @Given("^w输入寄件地址:(.+)$")

    public  void  wInput_sender(String from_address) throws Exception {
        if(CommonTools.checkElementExit(Constant.driverWeb,"className","multiTip")){
            WebElement send_address = Constant.driverWeb.findElement(By.className("from-address-info-address"));
            send_address.sendKeys(from_address);
            WebElement SelectAddress = Constant.driverWeb.findElement(By.xpath("/html/body/ul/li[1]/span[1]"));//选取检索第一个
            SelectAddress.click();
        }else {
//            Constant.driverWeb.findElement(By.className("from-address-info-address")).sendKeys(from_address);
            Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[1]/div[3]/table/tbody/tr[1]/td/div/div/input")).click();//点击输入框
            mapSearch(from_address);
        }

    }

    @Given("^w输入寄件地址详情：(.+)$")
    public void w输入取件地址详情(String addr) throws Throwable {
        WebElement address = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[1]/div[3]/table/tbody/tr[2]/td/input"));
        address.sendKeys(addr);
    }

    @Given("^w输入收件地址详情：(.+)$")
    public void w输入收件地址详情(String addr) throws Throwable {
        WebElement address = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[2]/table/tbody/tr[2]/td/input"));
        address.sendKeys(addr);
    }


    @Given("^w输入寄件人姓名:(.+)$")
    public void wEnterSenderName(String userName) {
        WebElement send_name = Constant.driverWeb.findElement(By.className("from-address-info-name"));
        send_name.sendKeys(userName);
    }
    @Given("^w输入寄件人手机号:(.+)$")
    public void wEnterSenderCellPhoneNumber(String sender_mobile) {
        Constant.driverWeb.findElement(By.className("from-address-info-phone")).sendKeys(sender_mobile);
    }

    @Given("^w输入收件人地址:(.+)$")
    public void wEnterRecipientAddress(String receive_address) throws Exception {
        if(CommonTools.checkElementExit(Constant.driverWeb,"className","multiTip")){
            WebElement send_address = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[2]/table/tbody/tr[1]/td[1]/div/div/input"));
            send_address.sendKeys(receive_address);
            WebElement SelectAddress = Constant.driverWeb.findElement(By.xpath("/html/body/ul/li[1]/span[1]"));//选取检索第一个
            SelectAddress.click();
        }else {
//            Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[2]/table/tbody/tr[1]/td[1]/div/div/input")).sendKeys(receive_address);
            Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[2]/table/tbody/tr[1]/td/div/div/input")).click();//点击输入框
            mapSearch(receive_address);
        }

    }

    @Given("^w输入收件人姓名:(.+)$")
    public void wEnterRecipientName(String name) {
        name = name == null ? "花千骨" : name;
        WebElement receive_name = Constant.driverWeb.findElement(By.className("to-address-info-name"));
        receive_name.sendKeys(name);
    }
    @Given("^w输入收件人姓名$")
    public void wEnterRecipientName() {
        wEnterRecipientName("娜美");
    }

    @Given("^w输入收件人手机:(.+)$")
    public void wEnterRecipientMobile(String recipientPhone) throws Throwable {
        recipientPhone = recipientPhone == null ? "15501213529" : recipientPhone;
        WebElement receive_phone = Constant.driverWeb.findElement(By.className("to-address-info-phone"));
        receive_phone.sendKeys(recipientPhone);
    }
    @Given("^w输入收件人手机$")
    public void wEnterRecipientMobile() throws Throwable {
        wEnterRecipientMobile("15501213579");
    }

    @Given("^w输入物品重量：(.+)$")
    public void wEnterItemWeigh(String weights) {
        weights = weights == null ? "5" : weights;
        WebElement weight = Constant.driverWeb.findElement(By.id("weight"));
        weight.clear();
        weight.sendKeys(weights);
    }

    @Given("^w输入物品名称$")
    public void w输入物品名称() throws Exception {
            wEnterItemName( null);
    }
    @Given("^w输入物品名称:(.+)$")
    public void wEnterItemName(String goodsName) throws Exception {
        goodsName = goodsName == null ? "文件" : goodsName;
        CommonTools.scrollToElement(Constant.driverWeb,By.xpath("//*[@id=\"goodsName\"]"));//滑动到下一步按钮
        WebElement ItemName = Constant.driverWeb.findElement(By.xpath("//*[@id=\"goodsName\"]"));
        try {
            ItemName.click();
        }catch (Exception e){
            Thread.sleep(3000);
            ItemName.click();
        }
        Thread.sleep(1000);
        ItemName.sendKeys(goodsName);
        CommonTools.waitElementLoad(Constant.driverWeb,"xpath","//*[@id=\"price-detail-btn\"]");
        CommonTools.scrollToElement(Constant.driverWeb,By.id("price-detail-btn"));
        Constant.driverWeb.findElement(By.id("price-detail-btn")).click();
        String premium=Constant.driverWeb.findElement(By.className("premium-fare")).getText();
//        System.out.println("溢价金额外："+premium);
        if (!Strings.isNullOrEmpty(premium)){
            Constant.orderFarePremium=Constant.driverWeb.findElement(By.className("premium-fare")).getText();
//            System.out.println("溢价金额ln："+Constant.orderFarePremium);
        }

    }

    @And("^w点击下一步$")
    public void wClickNext() throws Throwable {
        CommonTools.scrollToElement(Constant.driverWeb,By.id("saveInfo"));//滑动到下一步按钮
        Constant.driverWeb.findElement(By.id("saveInfo")).click();//点击下一步
        Thread.sleep(1500);
        CommonTools.waitElementLoad(Constant.driverWeb,"xpath","//*[@id=\"btn_modify\"]");
        wOrderNumbuter();
//        CommonTools.takeScreenShot(Constant.driverWeb,"aaaaa");
    }
    @And("^w点击下一步代收$")
    public void wDaiClickNex() throws Throwable {
        CommonTools.scrollToElement(Constant.driverWeb,By.id("saveInfo"));
        Constant.driverWeb.findElement(By.id("saveInfo")).click();
        Constant.driverWeb.findElement(By.id("saveInfo")).click();
        CommonTools.waitElementLoad(Constant.driverWeb,"xpath","//*[@id=\"btn_modify\"]");
        wOrderNumbuter();

    }
    @And("^w获取订单号$")
    public void wOrderNumbuter() throws Throwable {
        String str=Constant.driverWeb.getCurrentUrl();
        String orderNumber = CommonTools.cutEnd(str,"orderNumber=");
        Constant.testReport.add(orderNumber);
//        System.out.print("链接："+str);
//        String ss = Constant.orderURL;
//        Constant.OrderNumbuter.add(str.substring(ss.length(),str.length()));
        Constant.OrderNumbuter.add(orderNumber);
        System.out.println("订单号："+Constant.OrderNumbuter);
    }




    @Then(value = "^w确认订单总价:(\\d+)$")
    public void wConfirmTotalOrder(float order_count) throws Throwable {
        Constant.testReport.add("期待金额："+order_count);
        if (Method.night()){
            Constant.orderAmount = Constant.driverWeb.findElement(By.xpath(".//*[@id='total_money']")).getText();//夜晚优惠前总额
            Constant.testReport.add("页面订单总额："+Constant.orderAmount);
            BigDecimal OrderAmount = new BigDecimal(Constant.orderAmount);
            BigDecimal FarePremium = new BigDecimal(Constant.orderFarePremium);
            float OrderAmount2 = OrderAmount.subtract(FarePremium).floatValue();
            Assert.assertEquals(order_count+10F, OrderAmount2,0.000001);
        }
        else {
            Constant.orderAmount = Constant.driverWeb.findElement(By.xpath(".//*[@id='total_money']")).getText();//夜晚优惠前总额
            BigDecimal OrderAmount = new BigDecimal(Constant.orderAmount);
            BigDecimal FarePremium = new BigDecimal(Constant.orderFarePremium);
            float OrderAmount2 = OrderAmount.subtract(FarePremium).floatValue();
            Assert.assertEquals(order_count, OrderAmount2,0.000001);
        }


    }
    @Then(value = "^w提交订单$")
    public void wSubmitOrder() throws Throwable {
        Thread.sleep(1500);
        WebElement OrderActualAmount = Constant.driverWeb.findElement(By.id("use_balance"));
        Constant.orderBalancePayAm =OrderActualAmount.getText();//余额支付金额
        Constant.testReport.add("余额支付金额："+Constant.orderBalancePayAm);
//        System.out.println("余额支付金额："+Constant.orderBalancePayAm);
//        System.out.println("订单实际支付金额:"+Constant.OrderActualAmount);
        Constant.orderAmount = Constant.driverWeb.findElement(By.id("total_money")).getText();//订单总金额
        Constant.courierTotalIncome = Float.parseFloat(Constant.orderAmount) - Constant.orderMoto;
        CommonTools.waitElementLoad(Constant.driverWeb,By.id("final-submit-order"));//等待提交按钮出现
        Constant.driverWeb.findElement(By.id("final-submit-order")).click();//点击提交订单
        Thread.sleep(1500);
        boolean btn = CommonTools.checkElementExit(Constant.driverWeb,"xpath","//*[@id=\"myModal\"]/div/div/div[1]/span");//如果订单金额超过200，会弹出下单确认界面
        if (btn){
            Constant.driverWeb.findElement(By.id("submitOrder")).click();
        }
        Thread.sleep(2000);



    }
    @Then("^w获取取件密码$")
    public  void wGetPickupPassword() throws Throwable {
        Constant.driverWeb.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/ul/li[2]/a")).click();//点击上方我的闪送
        Thread.sleep(3000);
        WebElement PickupPassword =Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[1]/div[2]/table/tbody/tr[1]/td[5]/span"));
        Constant.PickupPassword = PickupPassword.getText();
    }

    @Then("^关闭浏览器$")
    public  void closeBrowser() throws Throwable {
        Constant.driverWeb.quit();
        Thread.sleep(2000);
    }

    @Then("^w切换城市到：(.+)$")
    public void wSwitchCity(String city) throws Throwable {
        Thread.sleep(1000);
        String nowCity =Constant.driverWeb.findElement(By.id("userCity")).getText();//当前城市
//        System.out.println("当前城市："+nowCity);
        if (nowCity .equals(city)){
//            System.out.println("当前城市与预期城市一直，无需切换");
        }else {
            Constant.driverWeb.findElement(By.id("selectCity")).click();//点击切换城市按钮
            //切换城市
            switchCity(city);
//            w点击城市名称(city);
        }
    }
    /**切换城市*/
    private String switchCity(String Cityname) throws Exception {
        List a = Constant.driverWeb.findElements(By.xpath("(//ul[@id='cityList']/li)"));
        for (int i = 1; i <= a.size(); i++) {
            WebElement ele = Constant.driverWeb.findElement(By.xpath("(//ul[@id='cityList']/li)["+ i +"]"));
            //System.out.println("(//ul[@id='cityList']/li)["+ i +"]");
            //System.out.println("i的值：" + i + "   对应城市为：" + ele.getText() + "   对应data_id值：" + ss);

            if (ele.getText().equals(Cityname)) {
                Constant.driverWeb.findElement(By.xpath("(//ul[@id='cityList']/li)["+ i +"]")).click();
                System.out.println("点击成功");
                return "Successed";
            }
        }
        return "Failed";
    }

    @Then("^w点击城市名称：(.+)$")
    public void w点击城市名称(String city) throws Throwable {
            Constant.driverWeb.findElement(By.id("currentCity")).click();
    }

//    private void switchCity(String cityName){
//        String LocationCity = Constant.driverWeb.findElement(By.id("currentCity")).getText();
//        if (LocationCity.equals(cityName)){
//            Constant.driverWeb.findElement(By.id("currentCity")).click();//点击当前定位城市
//        }else {
//            choiceCity(cityName);
//        }

//    }
    /**选择城市*/
    private void choiceCity(String cityName){
        for (int i = 0; i < 6; i++) {
            boolean isCity = CommonTools.checkElementExit(Constant.driverWeb,By.id("SS"));
            if (isCity){

            }
        }
    }

    @Then("^w城市切换成功：(.+)$")
    public void wVerifyCitySwitch(String city) throws Throwable {
        WebElement city1 = CommonTools.findElement(Constant.driverWeb,"id","userCity");//城市
        if (city.equals(city1.getText())){
           // System.out.println("切换正确");
        }else{
           // System.out.println("切换失败");
        }


    }

    @Then("^w输入订单备注:(.+)$")
    public void wEnterOrderRemark(String remark) throws Throwable {
        WebElement Remark = Constant.driverWeb.findElement(By.className("demoInfo"));
        remark = remark == null ? "速度、安全" : remark;
        Remark.sendKeys(remark);
    }

    @Then("^w选择预约取件$")
    public void w选择预约取件() throws Throwable {
        Thread.sleep(1000);
        CommonTools.scrollToElement(Constant.driverWeb,By.id("delayDelivery"));
        Constant.driverWeb.findElement(By.id("delayDelivery")).click();
    }

    @Then("^w选择预约取件：(.+)$")
    public void w选择预约取件取件时间(String time) throws Throwable {
        time = time == null ? "09" : time;//time为小时
        Constant.driverWeb.findElement(By.id("delayDelivery")).click();
        Thread.sleep(1000);
        Constant.driverWeb.findElement(By.id("appointmentDay")).click();//点击预约取件日期
        Constant.driverWeb.findElement(By.xpath("//*[@id=\"appointmentDay\"]/option[2]")).click();//选择预约第二天
        Constant.driverWeb.findElement(By.xpath("//*[@id=\"appointmentTimePicker\"]")).click();
        WebElement ele = Constant.driverWeb.findElement(By.xpath("/html/body/div[9]/table/tbody/tr[2]/td[1]/input"));
        ele.click();
        Actions action = new Actions(Constant.driverWeb);
        action.doubleClick(ele).perform();
        ele.sendKeys(time);



    }

    @Then("^确认此订单为预约单$")
    public void w确认此订单为预约单() throws Throwable {
        w进入我的闪送中();
        Assert.assertEquals(true,Method.qeuryAllOrderContent(Constant.OrderNumbuter.get(Constant.OrderNumbuter.size()-1),"预约时间"));




    }

    @Given("^w进入我的闪送中$")
    public void w进入我的闪送中() throws Throwable {
        Thread.sleep(2000);
        for (int i = 0; i < 4; i++) {
            CommonTools.scrollToElement(Constant.driverWeb,By.linkText("我的闪送"));
            Constant.driverWeb.findElement(By.linkText("我的闪送")).click();//点击上方“我的闪送”
            Thread.sleep(3000);
            String orderNum = Constant.driverWeb.findElement(By.id("today")).getText();
            if (!(orderNum.equals(null))){
                Thread.sleep(1000);
                break;
            }
        }

    }

    @Given("^w选择添加一个收件地址$")
    public void w选择添加一个收件地址() throws Throwable {
        Constant.driverWeb.findElement(By.className("plus")).click();
    }

    @Given("^w输入新添加收件地址与收件人信息：(.+)$")
    public void w输入新添收件地址与收件人信息收件人地址(String address) throws Throwable {
        WebElement address2 = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[3]/table/tbody/tr[1]/td[1]/div/div/input"));
        address2.sendKeys(address);
        if (CommonTools.checkElementExit(Constant.driverWeb,"className","help-address-a")){

        }else {
            WebElement SelectAddress = Constant.driverWeb.findElement(By.xpath("/html/body/ul/li[1]/span[1]"));
            SelectAddress.click();
        }

        WebElement name2 = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[3]/table/tbody/tr[3]/td/p/input"));
        name2.sendKeys("花非花");
        WebElement numbuter2 = Constant.driverWeb.findElement(By.xpath("//*[@id=\"container_wrapper\"]/div[2]/div[1]/div/div[2]/div[3]/table/tbody/tr[4]/td/p/input"));
        numbuter2.sendKeys("15501213579");

    }

    @Given("^w我的订单中确认订单状态：(.+)$")
    public void  w我的订单中确认刚提交的订单状态(String btn) throws Throwable {
        w进入我的闪送中();
        Assert.assertEquals(true,Method.qeuryAllOrderContent(Constant.OrderNumbuter.get(Constant.OrderNumbuter.size()-1),btn));
    }


    @Given("^w确认订单状态：(.+)$")
    public void w确认订单状态(String status) throws Throwable {
        Method.qeuryAllOrderContent(Constant.OrderNumbuter.get(Constant.OrderNumbuter.size()-1),status);

    }

    @Given("^测试等待$")
    public void 测试等待() throws Throwable {
        Thread.sleep(12000);
    }
    public void mapSearch(String address) throws Exception {
        Constant.driverWeb.findElement(By.className("baiduKey")).sendKeys(address);//弹出界面并输入地址
        Constant.driverWeb.findElement(By.className("searchBtn2")).click();//点击搜索
        Thread.sleep(1500);
        if (!(CommonTools.checkElementExit(Constant.driverWeb,"xpath","//*[@id=\"helpPanel\"]/div/div[1]/ol/li[1]/span"))){
            Constant.driverWeb.findElement(By.className("searchBtn2")).click();//点击搜索
        }
        Actions action = new Actions(Constant.driverWeb);
        CommonTools.waitElementLoad(Constant.driverWeb,"xpath","//*[@id=\"helpPanel\"]/div/div[1]/ol/li[1]/span");
        WebElement nav = Constant.driverWeb.findElement(By.xpath("//*[@id=\"helpPanel\"]/div/div[1]/ol/li[1]/span"));
        action.moveToElement(nav).build().perform();
        Constant.driverWeb.findElement(By.className("chooseAddrBtn")).click();//选取第一个搜索到的地址
    }

    @Given("^w我的闪送界面，切换城市到：(.+)$")
    public void w我的闪送界面切换城市到城市(String city) throws Throwable {
        Thread.sleep(1000);
        WebElement city1 = Constant.driverWeb.findElement(By.id("city"));//城市
        String x = city1.getText();
        if (x .equals(city)){
        }else {
            WebElement city2 = Constant.driverWeb.findElement(By.id("selectCity"));//城市选择
            city2.click();
            WebElement city3 = Constant.driverWeb.findElement(By.xpath("//*[@id=\"cityList\"]/li["+ WebCityId.getCityCodeByName(city)+"]"));
            city3.click();

        }
    }

    @Given("^w选择加价15元$")
    public void w选择加价元() throws Throwable {
        Thread.sleep(1000);
        w勾选我要加价();
        Constant.driverWeb.findElement(By.xpath("//*[@id=\"confirm_order_form\"]/div[2]/div/div[2]/div/div[3]/span")).click();

    }


    @Given("^w勾选我要加价$")
    public void w勾选我要加价() throws Throwable {
        Constant.driverWeb.findElement(By.id("play_overflow_price")).click();//点击加价按钮

    }


    @Given("^w确认订单提交成功$")
    public void w确认订单提交成功() throws Throwable {
        CommonTools.waitElementLoad(Constant.driverWeb,"className","color-green");
        String btn = Constant.driverWeb.findElement(By.className("color-green")).getText();
        Assert.assertEquals(btn,"感谢您使用闪送服务，订单提交成功！");

    }


    @Given("^w订单提交界面，确认公里数与公斤数：(.+)：(.+)$")
    public void w订单提交界面确认公里数与公斤数(String mile,String wight) throws Throwable {
        String chars = Constant.driverWeb.findElement(By.id("final_info")).getText();
        System.out.println("确认公里数与公斤数:"+chars);
        CommonTools.assertStringContain(chars,mile);
        CommonTools.assertStringContain(chars,wight);

    }

    @Given("^w订单提交界面，确认寄件人信息：(.+)：(.+)：(.+)：(.+)$")
    public void w订单提交界面确认寄件人信息(String sendName,String sendMlbile,String sendAdress,String room) throws Throwable {
        String chars = Constant.driverWeb.findElement(
                By.xpath("//*[@id=\"confirm_order_form\"]/div[1]/div/table/tbody/tr[1]/td/div")).getText();
        System.out.println("订单提交界面确认寄件人信:"+chars);
        CommonTools.assertStringContain(chars,sendName);
        CommonTools.assertStringContain(chars,sendMlbile);
        CommonTools.assertStringContain(chars,sendAdress);
        CommonTools.assertStringContain(chars,room);
    }


    @Given("^w订单提交界面，确认收件人信息：(.+)：(.+)：(.+)：(.+)$")
    public void w订单提交界面确认收件人信息(String pickupName,String pickupMlbile,String pickAdress,String room) throws Throwable {
        String chars = Constant.driverWeb.findElement(
                By.xpath("//*[@id=\"confirm_order_form\"]/div[1]/div/table/tbody/tr[2]/td")).getText();
        System.out.println("订单提交界面确认收件人信息:"+chars);
        CommonTools.assertStringContain(chars,pickupName);
        CommonTools.assertStringContain(chars,pickupMlbile);
        CommonTools.assertStringContain(chars,pickAdress);
        CommonTools.assertStringContain(chars,room);
    }

    @Given("^w订单提交界面，确认取件时间$")
    public void w订单提交界面确认取件时间() throws Throwable {
        String chars = Constant.driverWeb.findElement(
                By.xpath("//*[@id=\"confirm_order_form\"]/div[1]/div/table/tbody/tr[3]/td")).getText();
        System.out.println("订单提交界面确认收件人信息:"+chars);
        CommonTools.assertStringContain(chars,"立即取件");
    }

    @Given("^w今日订单中，验证寄件人与收件人信息：(.+)：(.+)：(.+)：(.+)：(.+)：(.+)：(.+)：(.+)：(.+)：(.+)$")
    public void w今日订单中验证寄件人与收件人信息注(String sendName,String sendMlbile,String sendAdress,String room,String pickupName,String pickupMlbile,String pickAdress,String room2,String goods,String bemarks) throws Throwable {
        String orderNum = Constant.OrderNumbuter.get(Constant.OrderNumbuter.size()-1);
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,sendName));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum, BusinessTools.phoneNumberLatterFour(sendMlbile)));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,sendAdress));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,room));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,pickupName));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,BusinessTools.phoneNumberLatterFour(pickupMlbile)));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,pickAdress));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,room2));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,goods));
        Assert.assertEquals(true,Method.qeuryAllOrderContent(orderNum,bemarks));
    }


}
